import React, { useEffect, useState } from "react";
import TagInput from "../../../TagInput";
import type { FieldBaseType } from "../../type";

interface SwitchFieldProps {
  field: FieldBaseType<
    Array<string>,
    { maxLength?: number; getPopupContainer?: () => HTMLElement }
  >;
  onChange: (value: Array<string>) => void;
}

export default function TagField({ field, onChange }: SwitchFieldProps) {
  const { value, defaultValue, disabled, options, meta } = field;

  const [innerOpts, setInnerOpts] = useState<Array<string>>([]);

  useEffect(() => {
    if (!options) return;
    if (typeof options == "function") {
      options().then((r) => {
        setInnerOpts(r.map((i) => i.value as string));
      });
    } else {
      setInnerOpts(options.map((i) => i.value as string));
    }
  }, [options]);

  const inputHandler = (text: string) => {
    if (typeof options == "function")
      options(text).then((r) => setInnerOpts(r.map((i) => i.value as string)));
  };

  const tags = value ?? defaultValue ?? [];

  return (
    <TagInput
      value={tags}
      onChange={onChange}
      disabled={disabled}
      onInputChange={inputHandler}
      options={innerOpts}
      maxLength={meta?.maxLength}
      getPopupContainer={meta?.getPopupContainer}
    />
  );
}
